/*
 * @Author: zhangchaosen
 * @Date: 2024-05-20 09:29:53
 * @LastEditors: zhangchaosen
 * @LastEditTime: 2024-06-18 13:45:16
 * @Description: 用户模块
 */
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

import piniaStore from '@/store'
import { loginApi, getInfoApi, logoutApi } from '@/api/login/user'
import { IPermissionsList, IUserInfoDetail } from '@/api/login/type'
import { type UserState } from '@/store/interface'
import { userModule } from '@/store/helper'
import { resetRouter } from '@/router'
import { removeToken, setToken } from '@/utils/cookies'

export const useUserStore = defineStore({
  id: 'geek-user',
  state: (): UserState => userModule(),
  getters: {
    // 获取 token
    getToken(): string {
      return this.token
    },
    // 获取用户信息
    getUserInfo(): IUserInfoDetail {
      return this.userInfo
    },
    getHasUerInfo(): boolean {
      return !!this.userInfo.userId
    },
    // 获取用户角色
    getUserRoleName(): string {
      return this.userRoleName
    },
    // 用户权限列表
    getPermissions(): IPermissionsList {
      return this.permissions
    },
    // 是否是管理员账号
    getIsAdminCount(): boolean {
      return this.isAdminCount
    }
  },
  actions: {
    /**
     * 重置 user modules 状态
     */
    resetUserModules() {
      const { token, userInfo, hasUserInfo, isAdminCount, permissions } = userModule()
      this.token = token
      this.userInfo = userInfo
      this.hasUserInfo = hasUserInfo
      this.isAdminCount = isAdminCount
      this.permissions = permissions
    },
    /**
     * 登录
     * @param userInfo (用户名和密码)
     * @returns
     */
    login(userInfo: LoginFormModule) {
      return new Promise<IApiResponseData>((resolve, reject) => {
        loginApi(userInfo)
          .then(res => {
            const { data } = res
            // 存 token
            this.token = data.token as unknown as string
            setToken(data.token)
            resolve(data)
          })
          .catch((err: any) => {
            reject(err)
          })
      })
    },
    /**
     * 获取用户信息
     */
    async getLoginUserInfo() {
      try {
        const res = (await getInfoApi()).data
        const { permissions, user } = res
        this.userInfo = user
        this.permissions = permissions || []
        if (user) {
          const { roleName, roleNameList } = user
          this.userRoleName = roleName || (Array.isArray(roleNameList) ? roleNameList[0] : '')
        }
        return this.userRoleName
      } catch (e) {
        console.log('获取用户信息错误', e)
        throw e
      }
    },
    /**
     * 退出登录
     */
    logout() {
      return new Promise<void>((resolve, reject) => {
        logoutApi()
          .then(async () => {
            await this.resetToken()
            ElMessage({ type: 'success', message: '退出登录成功' })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    /**
     * 删除 token
     */
    resetToken() {
      return new Promise<void>(resolve => {
        // 必须先删除token
        removeToken()
        // 再 reset
        this.resetUserModules()
        resetRouter()
        resolve()
      })
    }
  }
})

// 在 components 外部使用 store 需要先创建 pinia
// https://pinia.esm.dev/core-concepts/outside-component-usage.html#single-page-applications
export function useUserStoreHook() {
  return useUserStore(piniaStore)
}
